//
//  UIDevice+Ext.swift
//  ESVpn
//
//  Created by nkl on 2023/6/28.
//

import Foundation
import UIKit

extension UIDevice {
    public static func isIphone12() -> Bool {
        if UIDevice.current.userInterfaceIdiom != .phone {
            return false
        }
        let isIphone12Sizes = [
            CGSize(width: 428, height: 926),
            CGSize(width: 926, height: 428),
            CGSize(width: 390, height: 844),
            CGSize(width: 844, height: 390),
            CGSize(width: 360, height: 780),
            CGSize(width: 780, height: 360),
        ]
        return isIphone12Sizes.contains(UIScreen.kMainSize)
    }

    public static func isIPhoneXSeries() -> Bool {
        if UIDevice.current.userInterfaceIdiom != .phone {
            return false
        }

        let isXSeriesSizes = [
            CGSize(width: 414, height: 896),
            CGSize(width: 375, height: 812),
            CGSize(width: 896, height: 414),
            CGSize(width: 812, height: 375),
            CGSize(width: 428, height: 926),
            CGSize(width: 926, height: 428),
            CGSize(width: 390, height: 844),
            CGSize(width: 844, height: 390),
            CGSize(width: 360, height: 780),
            CGSize(width: 780, height: 360),
        ]
        if !isXSeriesSizes.contains(UIScreen.kMainSize) {
            if let mWindow = UIApplication.shared.delegate?.window {
                if #available(iOS 11.0, *) {
                    return mWindow?.safeAreaInsets.bottom ?? 0 > 0.0
                } else {
                    return false
                }
            }
        }
        return true
    }

    public static func statusBarHeight() -> CGFloat {
        if #available(iOS 13.0, *) {
            let defaultHeight = UIApplication.shared.windows.first?.windowScene?.statusBarManager?.statusBarFrame.size.height ?? 0.0
            return UIApplication.shared.windows.first?.safeAreaInsets.top ?? defaultHeight
        } else {
            var statusBarHeight = UIApplication.shared.statusBarFrame.size.height
            if statusBarHeight <= 0 {
                statusBarHeight = UIDevice.isIphone12() ? 50.0 : (UIDevice.isIPhoneXSeries() ? 44.0 : 20.0)
            }
            return statusBarHeight
        }
    }

    public static var navigationBarHeight: CGFloat {
        statusBarHeight() + 44.0
    }

    public static var tabBarHeight: CGFloat {
        isIPhoneXSeries() ? 84.0 : 50.0
    }

    public static var safeBottomMargin: CGFloat {
        isIPhoneXSeries() ? 34.0 : 0.0
    }
}
